﻿using System;
using System.IO;
using System.Text;
using System.Xml;

namespace CSharpExt.Xml
{
    public abstract class DocumentSerializer
    {

        public static String Serialize(XmlNode node)
        {
            return Serialize(node, "UTF-8");
        }

        public static String Serialize(XmlNode node, String options)
        {
            StringWriter sw = new StringWriter();
            Serialize(node, sw, options);
            return sw.ToString();
        }


        public static void Serialize(XmlNode node, TextWriter writer)
        {
            Serialize(node, writer, "UTF-8");
        }
        public static void Serialize(XmlNode node, TextWriter writer, String options)
        {
            XmlWriterSettings ws = parseOptions(options);
            using(XmlWriter w = XmlWriter.Create(writer, ws))
            {
                node.WriteTo((w));
                w.Flush();
                w.Close();
            }
        }


        public static void Serialize(XmlNode node, Stream writer)
        {
            Serialize(node, writer, "UTF-8");
        }
        public static void Serialize(XmlNode node, Stream writer, String options)
        {
            XmlWriterSettings ws = parseOptions(options);
            using (XmlWriter w = XmlWriter.Create(writer, ws))
            {
                node.WriteTo(w);
                w.Flush();
                w.Close();
            }
        }


        public static void SerializeToFile(XmlNode node, String filePath)
        {
            SerializeToFile(node, filePath, "UTF-8");
        }
        public static void SerializeToFile(XmlNode node, String filePath, String options)
        {
            FileStream writer = File.OpenWrite(filePath);
            Serialize(node, writer, options);
            writer.Close();
        }


        private static XmlWriterSettings parseOptions(String options)
        {
            XmlWriterSettings ws = new XmlWriterSettings();
            ws.Encoding = Encoding.UTF8;
            ws.Indent = true;
            ws.CloseOutput = false;

            // begin: qui' dovrebbe parsare le opzioni
            // end

            return ws;
        }
    }
}
